// pages/00login/login.js
var app = getApp()
var appData = app.globalData
var co = require('../js/common.js')
var M = require('../js/md5.js')
var _this
Page({
   data: {
      isShowInputLabelArr: [0, 0, 0],
      pxArrShow: [0, 0, 0, 0, 0],
      pxArr: [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
      shopInfo: '',
      loginBossInfo: '',
      loginWaiterInfo: '',
      loginGuestInfo: '',
      loginMode: 'guest',
      isNewGuest: '',
      tableInfo: '',
      order: '',
      setGuestNumShow: 0,//自定义弹窗参数
      regShow: 0,
      regInputShow: 0,
      numArray: [
         [1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12],
         [13, 14, 15, 0]],
      inviter: '',
      call: 0,
      authConfirm: 0
      //testImg: "../images/qzg_logo_90x_dark.jpg"  
   },
   loginData: {
      isShowSubmenu: [false, false, false, false, false, false, false, false, false, false, false, false, false],
      userInfo: ''
   },
   checkout: function () {
      wx.showToast({
         btnArrIsShow: false
      })
   },
   //弹框
   call: function () {
      this.setData({ call: !this.data.call })
      console.log('this.data.call', this.data.call)
   },
   callWaiter: function (e) {
      var o = this.data.order
      var m
      switch (e.currentTarget.id) {
         case '0': m = '结账'; break;
         case '1': m = '消菜'; break;
         case '2': m = '催菜'; break;
         case '3': m = '加汤'; break;
         case '4': m = '换盘'; break;
         case '5': m = '服务员'; break;
      }

      var msg = o.fenlei + o.zhuo + '要' + m

      var m = {
         msg: [0, 0, 0, 0, 0, 0],
         setMsg: msg
      }

      var json = {
         type: 'say',
         to_client_id: 'all',
         content: JSON.stringify(m)
      }
      var msg = JSON.stringify(json)
      appData.isWsSender = 1
      app.sendSocketMsg(msg)
      //console.log('可以的', e, msg)
   },

   onLoad: function (opt) {
      if (opt) {
         if (opt.hasOwnProperty('str')) {
            var obj = JSON.parse(opt.str)
            this.setData({ inviter: obj })
         }
      }
      _this=this
      var res = wx.getSystemInfoSync()
      this.setData({
         win_w: res.windowWidth - 60,
         win_h: res.windowHeight
      })

      this.wxLogin()
      this.setData({
         loginWaiterInfo: wx.getStorageSync('waiterInfo'),
         loginBossInfo: wx.getStorageSync('userInfo')
      })

      var t = this
      app.setNoticeTicket(function (notice) {
         console.log('顾客点完菜通知桌号小票===', notice)
         t.getTableInfo(notice)
      })

      // wx.getSetting({
      //    success: function(res) {
      //       console.log('【getSetting:success:res】',res)
      //    },
      //    fail: function(res) {
      //       console.log('【getSetting:success:res】', res)
      //    },
      // })
   },

   auth: function (e) {
      this.setData({ authConfirm: 0 })
      console.log('this.data==', this.data)
      var eid = e.currentTarget.id
      if (eid == "0") {
         var m = { userid: appData.guestInfo.userid }
         var json = {
            type: 'say',
            to_client_id: 'all',
            content: JSON.stringify(m)
         }
         var msg = JSON.stringify(json)
         app.sendSocketMsg(msg)
      }
      app.readyWebsocket()
   },

   wxLogin: function () {
      if (wx.showLoading) {
         wx.showLoading({ title: '加载中…' })
      } else {
         app.toast('加载中…(您微信未升级最新版)')
      }
      var t = this
      wx.login({
         success: function (res) {
            console.log('wx.login成功:res', res)
            t.loginQzg(res.code)
         },
         fail: function (res) {
            console.log('wx.login失败:res', res)
         },
      })
   },
   //微信识别登录
   loginQzg: function (code) {
      var param = {
         code: code,
         appid: 'wxec4b2d47b9a51eb6',
         secret: '1de3b6183409b2db3803ed7466d851fd',
      }
      var t = this
      app.getNetData('member/manage/wxlogin', param, function (res) {
         if (wx.hideLoading) wx.hideLoading()
         var rd = res.data
         t.setData({
            loginGuestInfo: rd,
            isNewGuest: res.code == 0 ? 0 : 1
         })
         appData.guestInfo = rd

         if (res.code == 0) t.getUserOrder(rd.userid)

         console.log('【微信识别登录】==', t.data)
      })
   },

   getUserOrder: function (userid) {
      var param = { userid: userid }
      var t = this
      app.getNetData('member/manage/getmemberorder', param, function (res) {
         var d = res.data
         var t_d = t.data
         if (!co.isEmpty(d.shopInfo)) {
            var s = { shopInfo: d.shopInfo }
            t.setData({ shopInfo: s })
            appData.shopInfo = s
         }
         if (!co.isEmpty(d.order)) {
            t.setData({ order: d.order })
            t.initWebsocket()
         }
         console.log('【获取识别用户订单】==', t.data)
      })
   },
   //扫描桌码
   scan: function (e) {
      var t_d = this.data
      if (t_d.isNewGuest == 0) {
         if (co.isEmpty(t_d.tableInfo)) {
            this.scanCode()
            return
         }
         if (t_d.tableInfo.status == 1) {//status==2的情况好像可以不用考虑
            this.setData({ setGuestNumShow: 1 })
         }
      } else {
         if (co.isEmpty(t_d.inviter)) {
            this.scanCode()
            return
         }
         if (t_d.inviter.hasOwnProperty('userid')) {
            this.setData({ regShow: 1 })
         }
      }
   },

   scanCode: function () {
      this.setData({
         setGuestNumShow: 0,
         regShow: 0
      })
      var t = this
      wx.scanCode({
         onlyFromCamera: true,
         success: function (res) {
            var str = res.result
            if (str.indexOf('qapi.openally.com/api/public/print') > -1) {
               var strArr = str.split('/')
               appData.rid = strArr[9]//赋值全局变量rid，rid有值就表示是授权
               console.log('准备授权确认appData==', appData)
               app.readyWebsocket(function (cb) {
                  console.log('@@@scanCode:====', cb)
                  if (cb.auth) {
                     t.setData({ authConfirm: 1 })
                  }
               })
            } else if (str.indexOf('www.openally.com/shop.php') > -1) {
               var strArr = str.split('=')
               t.getTableInfo(strArr[2])
            } else {
               app.toast('您扫的不是桥掌柜的二维码')
            }
         },
         fail: function (res) { },
      })
   },
   //获取桌号对应订单信息
   getTableInfo: function (tableId) {
      var param = { zhuo: tableId }
      var t = this
      app.getNetData('table/manage/getshoptableinfo', param, function (res) {
         var d = res.data
         var s = { shopInfo: d.shopInfo }
         t.setData({ shopInfo: s })
         appData.shopInfo = s

         if (t.data.inviter == '') {
            t.setData({ inviter: d.shopInfo })
         }
         delete d.shopInfo
         t.setData({ tableInfo: d })
         if (t.data.isNewGuest == 1) {
            t.setData({ regShow: 1 })//弹出注册
         } else {
            t.order(d)
         }
         console.log('获取桌信息后 t.data', t.data)
      })
   },
   //注册用户
   reg: function (urlEnd, userInfo) {
      var td = this.data
      userInfo.unionid = td.loginGuestInfo.unionid
      userInfo.rcduid = td.inviter.userid ? td.inviter.userid : td.shopInfo.shopInfo.userid
      var t = this
      app.getNetData(urlEnd, userInfo, function (res) {
         if (res.code == 0) {
            t.setData({
               loginGuestInfo: res.data,
               isNewGuest: 0,
               regShow: 0
            })
            t.order(t.data.tableInfo, 0)
            console.log('注册成功后 t.data', t.data)
         }
      })
   },

   order: function (d) {
      if (!appData.wssIsInit && !co.isEmpty(this.data.shopInfo)) {
         this.initWebsocket()
      }
      if (d.status == 2) {
         this.setData({ order: d })
      } else if (d.status == 1) {
         this.setData({ setGuestNumShow: 1 })
      } else {
         this.setData({ tableInfo: '' })
         if (d.status == 3) {
            app.modal('您刚扫描的' + d.fenlei + d.zhuo + '有人预订了')
         } else if (d.status == 0) {
            app.modal('您刚扫描的' + d.fenlei + d.zhuo + '关桌了，请咨询服务员')
         }
      }
      console.log('order:后 this.data', this.data)
   },
   //扫描桌码得到店铺信息后方能启动
   initWebsocket: function () {
      var t = this
      app.readyWebsocket(function (cb) {
         if (cb.msg[0] == t.data.order.id) {//是本桌才处理
            if (cb.msg[1] == 1) {
               t.setData({
                  order: '',
                  tableInfo: ''
               })
            }
            if (appData.isWsSender == 0) {
               t.getUserOrder(t.data.loginGuestInfo.userid)
               app.playMp3(0)
            } else {
               appData.isWsSender = 0
            }
         }
      })
   },

   getWxOpenInfo: function () {
      var t = this
      wx.getUserInfo({
         withCredentials: true,
         success: function (res) {
            console.log('UserInfo==', res)
            t.reg('member/manage/regwxinfo', res.userInfo)
            console.log('t.data.loginGuestInfo==', t.data.loginGuestInfo)
         },
         fail: function (res) {
            console.log('fail:UserInfo==', res)
         },
      })
   },

   // showInputLabel: function (e) {
   //    if (e.detail.value.length > 1) return;
   //    var index = e.currentTarget.id;
   //    var isShowArray = this.data.isShowInputLabelArr;
   //    isShowArray[index] = 1;
   //    this.setData({ isShowInputLabelArr: isShowArray })
   // },

   saveValue: function (e) {
      var w = wx.getStorageSync('waiterInfo')
      var info = co.isEmpty(w) ? {} : w
      var key = e.currentTarget.id
      info[key] = e.detail.value
      wx.setStorageSync('waiterInfo', info)
      this.setData({ loginWaiterInfo: info })
      // console.log('【this.data.loginWaiterInfo】', this.data.loginWaiterInfo)
   },
   //服务员快捷登录
   waiterWxBindLogin: function (e) {
      console.log('【waiterWxBindLogin:e】', e)
      var wxInfo = e.detail.userInfo
      var param = wx.getStorageSync('waiterInfo')
      param.unionid = appData.guestInfo.unionid
      param.nickName = wxInfo.nickName
      param.avatarUrl = wxInfo.avatarUrl
      console.log('【waiterWxBindLogin:w_param】', param)
      var t = this
      app.getNetData('shop/manage/' + e.currentTarget.id + 'BindLogin', param, function (res) {
         var r_d = res.data
         if (res.code == 0) {
            appData.shopInfo = r_d
            appData.guestInfo = r_d
            t.goto(r_d.shop_id)
         }
         if (res.code == 81) {
            app.confirm('重要提示！', res.msg, '确认登录', function (res) {
               if (res) {
                  appData.shopInfo = r_d
                  appData.guestInfo = r_d
                  t.goto(r_d.shop_id)
               }
            })
         }
         if (res.code == 92900) {
            app.toast(res.msg)
         }
      })
   },
   //提交输入注册
   inputReg: function (e) {
      if (this.data.regInputShow) {
         var e_v = e.detail.value
         e_v.password = M.md5(e_v.password)
         e_v.re_password = M.md5(e_v.re_password)
         this.reg('member/manage/reg', e_v)
      } else {
         this.setData({ regInputShow: 1 })
      }
   },
   //加菜
   addFood: function () {
      let tableStr = JSON.stringify(this.data.order)
      wx.navigateTo({
         url: '/pages/01homePage/02openTable/openTable?table=' + tableStr
      })
   },

   checkout: function () {
      app.toast('开发中……敬请期待！')
   },

   showRegLabel: function (e) {
      console.log('注册输入框e==', e)
      var l = e.detail.value.length
      if (l > 1) return;
      var index = e.currentTarget.id;
      var isShowArray = this.data.pxArrShow;
      isShowArray[index] = l ? 1 : 0;
      var pxArr = this.data.pxArr
      if (pxArr[index][0] == 0) {
         pxArr[index] = [(this.data.win_w + 60) * 0.1 + 25, this.data.win_h * 0.2 + e.target.offsetTop - 6]
         this.setData({ pxArr: pxArr })
      }
      this.setData({ pxArrShow: isShowArray })
   },

   maskHide: function () {
      this.setData({
         setGuestNumShow: 0,
         regShow: 0,
         call: 0,
         authConfirm: 0
      })
      if (this.data.authConfirm == 0) {
         app.readyWebsocket()
      }
   },
   //设置人数
   setGuestNum: function (e) {
      var num = e.currentTarget.id
      if (num > 0) {
         this.setData({ setGuestNumShow: 0 })
         var tab = this.data.tableInfo
         console.log('这个也是tab', tab)
         tab.guestNum = num
         var str = JSON.stringify(tab)
         wx.navigateTo({
            url: '/pages/01homePage/02openTable/openTable?table=' + str
         })
      } else {
         this.reSetNum(num)
      }
   },
   //重设数字
   reSetNum: function (num) {
      var nA = this.data.numArray
      for (var i = 0; i < nA.length; i++) {
         var nA2 = nA[i]
         for (var j = 0; j < nA2.length; j++) {
            if (num == 0) {
               if (nA[i][j] == 15) nA[i][j] = -1
               else if (nA[i][j] > 15) nA[i][j] += 14
               else if (nA[i][j] > 0) nA[i][j] += 15
            } else {
               if (nA[i][j - 1] == 14) nA[i][j] = 15
               else if (nA[i][j] > 29) nA[i][j] -= 14
               else if (nA[i][j] > 0) nA[i][j] -= 15
            }
         }
      }
      this.setData({ numArray: nA })
   },
   //切换登录模式
   toggleLogin: function (e) {
      var mode = ['guest', 'waiter', 'boss']
      var i = e.currentTarget.id
      this.setData({ loginMode: mode[i] })
      app.globalData.loginMode = mode[i]
   },

   // closeSocket: function () {
   //    app.closeSocket()
   // },

   //掌柜绑定+登录(接口会处理，已绑定过的直接登录，未绑定的先验证登录且绑定)
   submitLoginInfo: function (e) {
      console.log('appData.client_id.length===' + appData.client_id.length, 'appData', appData)
      if (appData.client_id.length == 20) {//如果登录着，先退出
         app.readyWebsocket()
      }
      console.log('提交的掌柜信息e：', e)
      // var e_d = e.detail
      var param = e.detail.value
      wx.setStorageSync('userInfo', param)
      if (param.pass != '') {
         param.pass = M.md5(param.pass)
      }
      console.log("param",param)
      app.getJsonData('biz/Bmg/bizLogin',param,function(res){
         if(res.code==0){
            console.log("【登录成功】",res)
            appData.shopInfo = res.data
            _this.goto(res.data.Biz_ID)
         }else{
            console.log("【用户名或密码错误】",res)
         }
      })
      // param.unionid = this.data.loginGuestInfo.unionid
      // var urlEnd = e_d.target.id == 'boss' ? 'BindLogin' : 'login'
      // var t = this
      // app.getNetData('shop/manage/boss' + urlEnd, param, function (res) {
      //    var r_d = res.data
      //    appData.shopInfo = r_d
      //    appData.guestInfo = r_d
      //    console.log('appData', appData)
      //    if (res.code == 0) {
      //       t.goto(r_d.shop_id)
      //    }
      //    if (res.code == 81) {
      //       app.toast(res.msg)
      //       setTimeout(function () {
      //          t.goto(r_d.shop_id)
      //       }, 1500)
      //    }
      //    if (res.code == 92900) {
      //       app.toast(res.msg)
      //    }
      // })
   },
   //服务员绑定+登录(接口会处理，已绑定过的直接登录，未绑定的先验证登录且绑定)
   submitWaiterInfo: function (e) {
      // console.log('appData.client_id.length===' + appData.client_id.length, 'appData', appData)
      if (appData.client_id.length == 20) {//如果登录着，先退出
         app.readyWebsocket()
      }
      var e_d = e.detail
      var param = e_d.value
      console.log('提交的服务员信息e：', param)
      wx.setStorageSync('waiterInfo', param)
      param.unionid = this.data.loginGuestInfo.unionid
      var t = this
      var urlEnd = e_d.target.id == 'wx' ? 'BindLogin' : 'login'
      app.getNetData('shop/manage/waiter' + urlEnd, param, function (res) {
         var r_d = res.data
         appData.shopInfo = r_d
         appData.guestInfo = r_d
         if (res.code == 0) {
            t.goto(r_d.shop_id)
         }
         if (res.code == 81) {
            app.toast(res.msg)
            setTimeout(function () { t.goto(r_d.shop_id) }, 1500)
         }
         if (res.code == 92900) {
            app.toast(res.msg)
         }
      })
   },

   goto: function (shop_id) {
      wx.switchTab({
         url: '/pages/01homePage/01home/home?userid=' + shop_id
      })
   },

   onPullDownRefresh: function () {
      this.reload('下')
   },

   onReachBottom: function () {
      this.reload('上')
   },

   reload: function (msg) {
      app.toast(msg + '拉刷新了')
      this.onLoad()
      this.setData({
         order: '',
         tableInfo: ''
      })
   },

   onShareAppMessage: function () {
      var userInfoStr = JSON.stringify(this.data.loginGuestInfo)
      return {
         title: this.data.loginGuestInfo.name + '邀请您来【桥掌柜】当掌柜',
         path: '/pages/00login/login?str=' + userInfoStr
      }
   }
})
